package com.hui.tset01.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * jwt工具类
 * @author hui
 */
public class JwtUtil {

    //jwt的过期时间
    public static final long TOKEN_EXPIRE_TIME = 1000L * 60 * 60 * 24;
    //jwt的签名密钥
    private static final String key = "huiUserKey:123456_hui_user_key_123456_at-least_32";
    private static final Key SECRET_KEY = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
    /**
     * 生成jwt
     * @param claims 存储的数据
     * @return jwt
     */
    public static String creatJwt(Map<String, Object> claims){
        JwtBuilder jwtBuild = Jwts.builder();
        return  jwtBuild
                .setHeaderParam("type","JWT") //设置头部的类型为JWT
                .setHeaderParam("alg","HS256")  // 设置签名算法为HS256
                .setClaims(claims)  // 设置存储的数据
                .setExpiration(new Date(System.currentTimeMillis()+TOKEN_EXPIRE_TIME))  // 设置过期时间
               .signWith(SECRET_KEY) // 设置签名密钥
               .compact();
    }

    /**
     * 解析jwt
     */
    public static Claims parseJwt(String token) {
        JwtParser jwtParser = Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build();
        return  jwtParser.parseClaimsJws(token).getBody();
    }
}
